"""Test Secure Controller"""
from pydive.lib.base import BaseController
from tg import expose, flash , require,redirect,validate
from tg import session
from repoze.what import predicates
from pylons.i18n import ugettext as _
from repoze.what.predicates import has_permission
from pydive.model import DBSession, metadata
from pydive.model.dive import Diver,Dive
from pydive.model.auth import User
from pylons.i18n import ugettext as _
from sqlalchemy.orm import eagerload
from sqlalchemy import desc , asc
from formencode import validators
from datetime import datetime
from dateutil.parser import parse
import transaction
from zope.sqlalchemy.datamanager import mark_changed 


import pprint


class LogBookController(BaseController):
    """REST Controller styled on the Atom Publishing Protocol"""
    # To properly map this controller, ensure your config/routing.py file has
    # a resource setup:
    #     map.resource('site', 'sites')
    
   
    allow_only = has_permission('logbook',
                                msg=_("You don't have a permission to view profile"))
   
    @expose(template="pydive.templates.logbook.index")
    def index(self,**kw):
        return dict(page='profile')
    
    @expose('json')
    def list(self, rows=1,page=1,sord='desc',sidx='date',**kw):
        l = int(rows)
        p = int(page)-1
        diver_id = session['user'].diver[0].id
        count = DBSession.query(Dive).filter(Dive.diver_id == diver_id).count()
        sort_fun = asc if sord == 'asc' else  desc
        dives = DBSession.query(Dive).filter(Dive.diver_id == diver_id).order_by(sort_fun(getattr(Dive,sidx))).limit(l).offset(p*l).all()
        #i+1 id must start from 1 not 0
        rows = []
        for i, dive in enumerate(dives):
            id = i+1
            action = "<div><div style='display:inline;float:left'><span class='.ui-state-hover ui-corner-all ui-icon ui-icon-trash'  title='delete' onclick='del("+str(dive.id)+")'/></div><div style='display:inline'><span class='ui-icon ui-icon-pencil' title='edit' onclick=\"window.location = '/logbook/edit/"+str(dive.id)+"'\"/></div></div>"
            rows.append({'id': id , 'cell':[action,dive.date,dive.duration,dive.greatestdepth,dive.lowesttemperature,dive.notes] })
        data= dict(page=page,total=int(count/l)+1,records=count,rows=rows)
        return data
    
    @expose('json')
    @validate(validators={"date":validators.NotEmpty(),'duration':validators.Number(),'greatestdepth':validators.Number(),'lowesttemperature':validators.Number()} , error_handler=index)
    def add_dive(self,date=None,duration=None,greatestdepth=None,lowesttemperature=None,notes=None):
        print "date:",date ," duration: ", duration," greatestdepth: ", greatestdepth," lowesttemperature: ", lowesttemperature," notes: ", notes
        diver_id = session['user'].diver[0].id
        try :
            datef = parse(date)
        except (ValueError):
            return _("Error: can not parse date")
        dive = Dive()
        dive.date=datef
        dive.duration=duration
        dive.greatestdepth=greatestdepth
        dive.lowesttemperature = lowesttemperature
        dive.diver_id = diver_id
        dive.notes = notes
        print "Dive to be added:date(",dive.date,")"
        DBSession.add(dive)
        return _("Added Successfully")
    
    @expose('json')
    @validate(validators={"id":validators.NotEmpty()} , error_handler=index)
    def del_dive(self,id=None):
        diver_id = session['user'].diver[0].id
        DBSession.query(Dive).filter(Dive.id==int(id)).filter(Dive.diver_id==diver_id).delete()
        # session wasn't marked as changed so i need to do it manualy 
        mark_changed(DBSession())
        return _("Removed Successfully")
  
    @expose(template="pydive.templates.logbook.dive")    
    def add(self, **kw):
        return dict(title="Add new dive",mode="add",dive=None)
    @expose(template="pydive.templates.logbook.dive")    
    def edit(self,id=None, **kw):
        diver_id = session['user'].diver[0].id
        dive = DBSession.query(Dive).filter(Dive.id==int(id)).filter(Dive.diver_id==diver_id).first();
        return dict(title="Edit dive",mode="edit",dive=dive)
    @expose(template="pydive.templates.logbook.dive")    
    def view(self,id=None, **kw):
        diver_id = session['user'].diver[0].id
        dive = DBSession.query(Dive).filter(Dive.id==int(id)).filter(Dive.diver_id==diver_id).first();
        return dict(title="Edit dive",mode="view",dive=dive)
    @expose()    
    def save(self,id=None,**kw):
        diver_id = session['user'].diver[0].id
        if id is None or id =='' :
            dive = Dive()
        else :
            dive = DBSession.query(Dive).filter(Dive.id==int(id)).filter(Dive.diver_id==diver_id).first();
        date = kw['date'] 
        h = kw['dateHour']
        m = kw['dateMinute']
        s = kw['dateSecond']
        if h != "": 
            date+=u" "+h
            if m!='' :
                date+=u":"+m
                if s!='':
                     date+=u":"+s
        dive.date=parse(date)
        dive.duration= 0 if kw['duration']== ''else kw['duration']
        dive.greatestdepth = 0 if kw['greatestdepth']== ''else kw['greatestdepth']
        dive.lowesttemperature = 0 if kw['lowesttemperature']== ''else kw['lowesttemperature']
        dive.notes = kw['notes']
        dive.diver_id=diver_id
        if id is None or id =='' :
            DBSession().add(dive)
        else:
            DBSession().update(dive)
        flash(_("Dive saved Successfully"))
        redirect('/logbook')

   
